#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int n, m, k, k1, c[N], T, x[5];
long long a[N];
char d[110];
int main() {
    freopen("arena.in", "r", stdin);
    freopen("arena.out", "w", stdout);
    ios::sync_with_stdio(false);
    cin.tie(0); cout.tie(0);
    cin >> n >> m;
    for(int i = 1; i <= n; i++) {
        cin >> a[i];
    }
    for(int i = 1; i <= m; i++) {
        cin >> c[i];
    }
    cin >> k1;
    for(int i = 1; i <= 14; i++) {
        if(pow(2, i) >= k1) {
            k = i;
            break;
        }
    }
    for(int i = 1; i <= k; i++) {
        cin >> d[i];
    }
    cin >> T;
    while(T--) {
        memset(x, 0, sizeof(x));
        for(int i = 1; i <= 4; i++) {
            cin >> x[i];
        }
        if(x[1] == 2 && x[2] == 1 && x[3] == 0 && x[4] == 0) cout << 5 << '\n';
        if(x[1] == 1 && x[2] == 2 && x[3] == 1 && x[4] == 0) cout << 19 << '\n';
        if(x[1] == 0 && x[2] == 2 && x[3] == 3 && x[4] == 1) cout << 7 << '\n';
        if(x[1] == 2 && x[2] == 2 && x[3] == 0 && x[4] == 1) cout << 1 << '\n';
    }
    return 0;
}
